<template>
  <div>
    <div id="tools">
      <!--日志查询-->
      <div class="height8"></div>
      <!-- 查询条件 -->
      <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">

        <a-form-item label="选择日期" class="marginBtm">
          <a-config-provider :locale="localezh_CN">
            <a-range-picker @change="onChangePicker" :locale="localezh_CN" :default-value="[startDate, endDate]" format="YYYY-MM-DD"/>
          </a-config-provider>
        </a-form-item>

        <a-form-item label="关键字" class="marginBtm">
          <a-input v-model="queryValue" allowClear placeholder="请输入操作人,IP" class="marginBtm"
                   @pressEnter="inquireStart"/>
        </a-form-item>

        <a-form-item label="操作类型" class="marginBtm">
          <!--99全部1出2进-->
          <a-dropdown style="">
            <a-menu slot="overlay" @click="carMenuClick">
              <a-menu-item :key="item.value" v-for="item in operationstype">{{item.name}}</a-menu-item>
            </a-menu>
            <a-button>{{ operationValue }}
              <a-icon type="down"/>
            </a-button>
          </a-dropdown>
        </a-form-item>


        <a-form-item class="marginBtm">
          <a-button type="primary" @click="inquireStart">
            查询
          </a-button>
        </a-form-item>

      </a-form>
      <a-divider style="margin: 5px 0"/>
      <div style="padding: 5px 10px 10px 10px;text-align: left;">
        <a-button type="primary" class="button-marin" @click="exportList">
          导出
        </a-button>
      </div>
    </div>

    <a-table
      class="tabled"
      bordered
      :fixed="true"
      size="small"
      :columns="columns"
      :row-key="record => record.id"
      :rowSelection="{type:'radio',selectedRowKeys:selectedRowKeys,fixed:true,onChange:onChange}"
      :customRow="clickRow"
      :data-source="tableData"
      :pagination="pagination"
      :loading="loading"
      :scroll="{ x:xWidth,y: yHeight }"
      :locale="localezh_CN"
      @change="handleTableChange"
    >
      <!--点击行选中行，点击单选按钮选中行；但是需要:row-key是唯一标示字段-->

      <!-- <template slot="name" slot-scope="name"> {{ name.first }} {{ name.last }} </template> -->
    </a-table>
  </div>
</template>

<script>
import { tableBoxHeight } from '@/api/communal'
import logApi from '@/api/log'
// eslint-disable-next-line camelcase
import localezh_CN from 'antd/lib/locale-provider/zh_CN'
// eslint-disable-next-line no-unused-vars
import { ConfigProvider } from 'ant-design-vue'// 引用
import 'moment/locale/zh-cn'
import moment from 'moment'
import cfg from '@/config/config'

export default {
  components: {
    // eslint-disable-next-line vue/no-unused-components
    ConfigProvider
  },
  name: '',
  data () {
    return {
      localezh_CN,
      spinning: false,
      importVisible: false,
      importLoading: false,
      fileList: [],
      errorMessage: '',
      operationstype: [
        { name: '全部', value: 99 }
      ],
      operationValue: '全部',
      operationId: '99',
      delayTime: 500,
      confirmLoading: false,
      modalData: null,
      xWidth: '',
      yHeight: '',
      tableData: [],
      pagination: {
        pageSize: 30,
        current: 1,
        total: 100,
        showSizeChanger: true,
        // showQuickJumper: true,
        pageSizeOptions: ['30', '50', '100'],
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => {
          // console.log("1111");
          this.pagination.current = 1
          this.pagination.pageSize = pageSize
        }
      },
      selectedRowKeys: [],
      selectedRows: null,
      loading: false,
      dateFormat: 'YYYY/MM/DD HH:mm',
      startDate: '',
      endDate: '',
      startDated: '',
      endDated: '',
      modalStartDated: '', // 弹窗开始日期
      modalEndDated: '', // 弹窗结束日期
      queryValue: '', // 查询操作人 IP
      columns: [], // 表格表头
      visible: false
    }
  },

  beforeMount: function () {
    this.columns = [
      {
        title: '序号', // 表头
        dataIndex: 'serialNumber', // 字段名称
        width: '50px', // 设列宽度
        align: 'center', // 居中显示
        className: 'changeBack', // 重置覆盖背景色为浅灰色，否则是白色的
        customRender: (value, row, index) => `${(this.pagination.current - 1) * this.pagination.pageSize + index + 1}` // 设置动态序号
      },
      {
        title: '操作人',
        dataIndex: 'username',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '操作功能',
        dataIndex: 'operation',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: 'IP',
        dataIndex: 'ip',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '操作时间',
        dataIndex: 'createDate',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      }
    ]
    this.startDate = moment().startOf('month')
    this.endDate = moment().endOf('month')
    this.startDated = moment(this.startDate).format('YYYY-MM-DD')
    this.endDated = moment(this.endDate).format('YYYY-MM-DD')
    this.getOperationList()
  },
  mounted () {
    this.yHeight = tableBoxHeight() + 3 + 'px'
    this.xWidth = this.getTableWidth()
    const minHeight = document.getElementsByClassName('ant-table')
    minHeight[0].style.minHeight = tableBoxHeight() + 40 + 'px'
    this.inquireStart()
  },
  methods: {
    // 查询条件选择日期
    onChangePicker (date, dateString) {
      // console.log(date, dateString);
      this.startDated = dateString[0]
      this.endDated = dateString[1]
    },
    // 弹窗选择日期
    modalChangePicker (date, dateString) {
      // console.log(date, dateString);
      this.modalStartDated = dateString[0]
      this.modalEndDated = dateString[1]
    },
    // 获取操作类型
    async getOperationList () {
      const resp = await logApi.getOperationList()
      if (resp.data.success) {
        // console.log(resp.data.result)
        this.operationstype = [...this.operationstype, ...resp.data.result]
      } else {
        this.$message.error(resp.data.message)
      }
    },
    // 操作类型下拉菜单
    carMenuClick (e) {
      this.operationstype.filter(el => {
        // eslint-disable-next-line eqeqeq
        if (el.value == e.key) {
          this.operationValue = el.name
          this.operationId = el.value
        }
      })
    },
    // 计算表格宽度
    getTableWidth () {
      let totals = null
      var el
      for (el of this.columns) {
        totals += parseInt(el.width)
      }
      return totals + 100 + 'px'
    },
    // 开始查询
    inquireStart () {
      this.pagination.current = 1
      this.selectedRowKeys = []
      this.selectedRows = null
      // 如果增加查询条件，导出里面也要增加，条件一样
      const param = {
        current: this.pagination.current,
        pageSize: this.pagination.pageSize,
        startDate: this.startDated,
        endDate: this.endDated,
        serchTxt: this.queryValue,
        operation: this.operationId
      }
      // console.log(param);
      this.fetch(param)
    },
    // 点击行
    clickRow (record) {
      return {
        on: {
          click: () => {
            console.log(record)
            const keys = []
            keys.push(record.id) // 行数据一定要有唯一识别标志，否则无法选中，和表格的key一致
            this.selectedRowKeys = keys
            this.selectedRows = record
          }
        }
      }
    },
    // 表格切换分页
    handleTableChange (pagination, filters, sorter) {
      // console.log(pagination);
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.fetch({
        pageSize: pagination.pageSize,
        current: pagination.current,
        startDate: this.startDated,
        endDate: this.endDated,
        serchTxt: this.queryValue,
        operation: this.operationId,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      })
    },
    onChange (selectedRowKeys, selectedRows) {
      console.log(selectedRowKeys, selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows[0]
    },
    // 请求表格数据
    async fetch (params) {
      this.loading = true
      const resp = await logApi.getBdSysLogList(params)
      console.log(resp.data)
      if (resp.data.success) {
        this.loading = false
        this.pagination.total = resp.data.result.total
        this.tableData = resp.data.result.records
      } else {
        this.loading = false
        this.$message.error(resp.data.message)
      }
    },
    // 导出列表
    exportList () {
      // eslint-disable-next-line eqeqeq
      if (this.startDated == '') {
        this.$message.warning('开始日期不能为空')
        return
      }
      // eslint-disable-next-line eqeqeq
      if (this.endDated == '') {
        this.$message.warning('结束日期不能为空')
        return
      }

      this.spinning = true
      const param = {
        current: this.pagination.current,
        pageSize: this.pagination.pageSize,
        startDate: this.startDated,
        endDate: this.endDated,
        serchTxt: this.queryValue,
        operation: this.operationId
      }
      const jsonIn = encodeURI(encodeURI(JSON.stringify(param)))
      window.open(cfg.apiUrl + 'api/sys/log/exportBdSysLogList?jsonIn=' + jsonIn, '_self')
      this.spinning = false
    }
  }
}
</script>

<style scoped>
.marginBtm {
  margin-bottom: 5px;
}

</style>
